<template>
  <div class="category-tree">
    <el-tree
      v-loading="categoryTree.loading"
      ref="treeRef"
      show-checkbox
      highlight-current
      :check-strictly="checkStrictly"
      :data="categoryTree.dataSource"
      :node-key="categoryTree.nodeKey"
      :props="categoryTree.props"
      @check="getCheckedNodes"
    />
  </div>
</template>
<script>
import {
  ID_KEY,
  NAME_KEY,
  CODE_KEY,
} from '../constants';
export default {
  name: 'CategoryTree',
  props: {
    checkStrictly: {
      type: Boolean,
      default: false,
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
    checkedList: {
      type: Array,
      default: () => [],
    },
  },
  data () {
    return {
      categoryTree: {
        loading: false,
        dataSource: [],
        nodeKey: ID_KEY,
        props: {
          children: 'children',
          label: data => {
            return `${data[NAME_KEY]} ${data[CODE_KEY]}`
          },
        },
      },
    }
  },
  watch: {
    dataSource: {
      handler (val) {
        this.categoryTree.dataSource = val
      },
      immediate: true,
    },
    checkedList: {
      handler (val) {
        val = val ?? []
        this.$refs.treeRef?.setCheckedKeys(val.map(item => item[ID_KEY]))
      },
      immediate: true,
    },
  },
  methods: {
    // 获取选中的品类
    getCheckedNodes () {
      const curCheckNodes = this.$refs.treeRef?.getCheckedNodes() ?? []
      this.$emit('checked', curCheckNodes)
    },
  },
}
</script>
<style lang="less" scoped>
.category-tree {
  height: 400px !important;
  overflow: auto;
  margin: 10px 0px;
  border: 1px solid #ebeef5;
}
</style>
